//
//  FriendsViewController.m
//  FootPrint
//
//  Created by alex tao on 2/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "FriendsViewController.h"
#import "FriendSelCell.h"
#import "FriendDetailViewController.h"
#import "GroupDetailViewController.h"
#import "CompatibleUtil.h"
#import "InviteViewController.h"
#import "MatchFriendViewController.h"


@interface FriendsViewController ()

@end

@implementation FriendsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _parser = [[FriendParser alloc] init];
        _parser.delegate = self;
        _parser.addDelegate = self;
        _parser.inviteDelegate = self;
        _parser.friendDelDelegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:NOTIFY_REFRESH_FRIEND object:nil];
    [_btnAdd setHidden:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self updateVisiableView];
    [_parser inviteRequest:[GConfig getUserId]];
    
}

- (IBAction)actionAddGroup:(id)sender {
    
    if (_segmentControl.selectedSegmentIndex == 1) {
        
        GroupDetailViewController * detail = [[[GroupDetailViewController alloc] initWithNibName:@"GroupDetailViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = self.navigationController;
        if (nil == navVc) {
            navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        } else {
            [navVc pushViewController:detail animated:YES];
        }
        detail.eMode = eGroupModeCreate;
        
    } 

}

- (void)refreshData{
     [_parser updateFriendListForUid:[GConfig getUserId]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_parser release];
    self.allGroup = nil;
    self.allFriends = nil;
    [_segmentControl release];
    [_friendTable release];
   
    [_textField release];
    [_btnRightTitle release];
    [_btnAdd release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setSegmentControl:nil];
    [self setFriendTable:nil];
    [self setTextField:nil];
    [self setBtnRightTitle:nil];
    [self setBtnAdd:nil];
    [super viewDidUnload];
}

- (IBAction)changeSegment:(id)sender {
    [self updateVisiableView];
}

- (IBAction)moreOption:(id)sender {
    if (_segmentControl.selectedSegmentIndex == 0) {
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                  delegate:self
                                                         cancelButtonTitle:@"取消"
                                                    destructiveButtonTitle:nil
                                                         otherButtonTitles:@"从通讯录", @"输入账号", @"输入手机号",@"待确认" ,nil];
        UIViewController * rootVc = ROOT_VC;
        [actionSheet showInView:rootVc.view];
        [actionSheet release];
        
    }
}

- (void) updateVisiableView
{
    if (_segmentControl.selectedSegmentIndex == 0) {
        
        [_btnAdd setHidden:YES];
        [_btnRightTitle setHidden:NO];
        if ([FriendManager sharedInstance].isLatestList) {
            [self listUpdated:[[FriendManager sharedInstance] allFriends]];
        } else {
            [_parser updateFriendListForUid:[GConfig getUserId]];
        }
    } else {
        [_btnAdd setHidden:NO];
        [_btnRightTitle setHidden:YES];
        if ([FriendManager sharedInstance].isLatestGroup) {
            [self groupUpdated:[[FriendManager sharedInstance] allGroup]];
        } else {
            [_parser updateGroupListForUid:[GConfig getUserId]];
        }
    }
}

- (void)listUpdated:(NSArray*)alls
{
    self.allFriends = alls;
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        [_friendTable reloadData];
    }
}

- (void)groupUpdated:(NSArray*)alls
{
    self.allGroup = alls;
    
    if (_segmentControl.selectedSegmentIndex == 1) {
        [_friendTable reloadData];
    }
}

- (void)didFinishInviteDelegate:(FriendInvitationResponseMessage*)result{

    if(result != nil && [result resultCode]==0){
        if([result invitationList] != nil && [[result invitationList] count]>0){
            [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFY_INVITE object:nil];
        }
    }
}
- (void)failInvite{

}


#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString * title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"从通讯录"]) {
       
        MatchFriendViewController * matchVC = [[[MatchFriendViewController alloc] initWithNibName:@"MatchFriendViewController" bundle:nil] autorelease];
        [matchVC setNeedBack:YES];
        UINavigationController * navVc = self.navigationController;
        if (nil == navVc) {
            navVc = [[[UINavigationController alloc] initWithRootViewController:matchVC] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        } else {
            [navVc pushViewController:matchVC animated:YES];
        }
        
        /*
         下面的代码：从通讯录获取一个号友
         */
//        ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
//        NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty], nil];
//        picker.displayedProperties = displayedItems;
//        picker.peoplePickerDelegate = self;
//        
//        
//        [self presentModalViewController:picker animated:YES];
       // [self.navigationController pushViewController:picker animated:YES];

    } else if ([title isEqualToString:@"输入账号"]) {
        
        _alertView = [[UIAlertView alloc] initWithTitle:@"输入好友账号" message:@" " delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"发送", nil];
        _alertView.tag = 2;
        [_textField setFrame:CGRectMake(12, 40, 260, 31)];
        if (!IPHONE_OS_EQUILORHIGHERTHAN(@"4.0")) {
            CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 110.0);
            [_alertView setTransform:myTransform];
        }
        [_alertView addSubview:_textField];
        [_alertView show];
        
    } else if ([title isEqualToString:@"输入手机号"]) {
        
        _alertView = [[UIAlertView alloc] initWithTitle:@"输入好友手机号" message:@" " delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"发送", nil];
        _alertView.tag = 3;
        [_textField setFrame:CGRectMake(12, 40, 260, 31)];
        if (!IPHONE_OS_EQUILORHIGHERTHAN(@"4.0")) {
            CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 110.0);
            [_alertView setTransform:myTransform];
        }
        [_textField setText:@""];
        [_alertView addSubview:_textField];
        [_alertView show];
        
    } else if([title isEqualToString:@"待确认"]){
        
        InviteViewController * invate = [[[InviteViewController alloc] initWithNibName:@"InviteViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = self.navigationController;
        if (nil == navVc) {
            navVc = [[[UINavigationController alloc] initWithRootViewController:invate] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        } else {
            [navVc pushViewController:invate animated:YES];
        }
    }
}




- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{

    [self dismissModalViewControllerAnimated:YES];
    
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{

    ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (phones) {
        int phoneCount = ABMultiValueGetCount(phones);
        if (phoneCount == 1){ //仅在只有１个的电话号码时完成选择
            NSString *phoneNum = (NSString *)ABMultiValueCopyValueAtIndex(phones, 0);
			CFRelease(phones);
            //[phoneNoText setText:[self fixText:phoneNum]];
            
            
            _alertView = [[UIAlertView alloc] initWithTitle:@"好友手机号" message:@" " delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"发送", nil];
            _alertView.tag = 3;
            [_textField setFrame:CGRectMake(12, 40, 260, 31)];
            if (!IPHONE_OS_EQUILORHIGHERTHAN(@"4.0")) {
                CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 110.0);
                [_alertView setTransform:myTransform];
            }
            [_textField setText:[self fixText:phoneNum]];
            [_alertView addSubview:_textField];
            [_alertView show];
            
            
            
            [peoplePicker dismissModalViewControllerAnimated:YES];
            return NO;
        } else {
			CFRelease(phones);
            return YES;
        }
    }
    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    
    ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(phones, identifier);
    NSString *phoneNum = (NSString *)ABMultiValueCopyValueAtIndex(phones, index);
    
    _alertView = [[UIAlertView alloc] initWithTitle:@"好友手机号" message:@" " delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"发送", nil];
    _alertView.tag = 3;
    [_textField setFrame:CGRectMake(12, 40, 260, 31)];
    if (!IPHONE_OS_EQUILORHIGHERTHAN(@"4.0")) {
        CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 110.0);
        [_alertView setTransform:myTransform];
    }
    [_textField setText:[self fixText:phoneNum]];
    [_alertView addSubview:_textField];
    [_alertView show];
    
   // [phoneNoText setText:[self fixText:phoneNum]];
    
	CFRelease(phones);
    [peoplePicker dismissModalViewControllerAnimated:YES];
	return NO;
}


- (NSString *)fixText:(NSString *)text {
    if (text == nil) {
        return text;
    }
    NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
    for (int i=[text length] - 1; i >= 0; i--) {
        unichar ch = [text characterAtIndex:i];
        if (ch >= '0' && ch <= '9') {
            [result insertString:[NSString stringWithFormat:@"%c", ch] atIndex:0];
        }
        if ([result length] == 11) {
            break;
        }
    }
    return result;
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView.tag == 2){
        //NSString* cont = _textField.text;
       
    } else if(alertView.tag == 3){
        [self setSendingPhone:_textField.text];
        [_parser addFriendByPhone:_sendingPhone];
    }
}


- (void)didAddByPhone:(PhoneNoCheckResponseMessage*)result{
    
    if(result == nil || result.resultCode != 0){
        [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
    }
    
    int count = [[result checkResultList] count];
    BOOL isExit = NO;
    long long userId = 0;
    for(int i=0; i<count; i++){
        NSString* phone = [[result checkResultListAtIndex:i] phone];
        if([phone compare:_sendingPhone] == NSOrderedSame){
            isExit = YES;
            userId = [[result checkResultListAtIndex:i] userId];
            break;
        }
    }
    if(isExit && userId > 0){
        [_parser addFriendByUid:userId myId:[GConfig getUserId]];
    }
    
}
- (void)failAddByPhone{

    [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
    
}

- (void)didAddByUid:(FriendAddResponseMessage*)result{

    if(result != nil && [result resultCode] == 0){
    
        [[[iToast makeText:@"已发送请求，等待好友回应"] setDuration:2000] show];
        return;
    }
    [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
}
- (void)failAddByUid{

    [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        if (_segmentControl.selectedSegmentIndex == 1) {
            GroupMessage * msg = [_allGroup objectAtIndex:indexPath.row];
            [[GAlertLoadingView sharedAlertLoadingView] show];
            [_parser deleteGroup:[GConfig getUserId] forGroupId:msg.id];
        } else {
            FriendQueryResponseMessage_FriendList * msg = [_allFriends objectAtIndex:indexPath.row];
            [[GAlertLoadingView sharedAlertLoadingView] show];
            [_parser delFriendByUid:msg.user.id myId:[GConfig getUserId]];
        }
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_segmentControl.selectedSegmentIndex == 1) {
        return self.allGroup.count;
    }
    return self.allFriends.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *friendSelCellIdentifier = @"friendSelCellIdentifier";
    FriendSelCell *cell = [tableView dequeueReusableCellWithIdentifier:friendSelCellIdentifier];
    if (cell == nil) {
        cell = [[[FriendSelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendSelCellIdentifier] autorelease];
    }
    
    if (_segmentControl.selectedSegmentIndex == 1)
    {
        GroupMessage * msg = [_allGroup objectAtIndex:indexPath.row];
        [cell updateCellGroupInfo:msg];
    }
    else
    {
        FriendQueryResponseMessage_FriendList * msg = [_allFriends objectAtIndex:indexPath.row];
        [cell updateCellInfo:msg];
    }
    
    cell.redioImage.hidden = YES;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_segmentControl.selectedSegmentIndex == 1)
    {
        GroupMessage * msg = [_allGroup objectAtIndex:indexPath.row];
        
        GroupDetailViewController * detail = [[[GroupDetailViewController alloc] initWithNibName:@"GroupDetailViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = self.navigationController;
        if (nil == navVc) {
            navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        } else {
            [navVc pushViewController:detail animated:YES];
        }
        detail.groupMsg = msg;
    }
    else
    {
        FriendQueryResponseMessage_FriendList * msg = [_allFriends objectAtIndex:indexPath.row];
        
        FriendDetailViewController * detail = [[[FriendDetailViewController alloc] initWithNibName:@"FriendDetailViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = self.navigationController;
        if (nil == navVc) {
            navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        } else {
            [navVc pushViewController:detail animated:YES];
        }
        detail.activityBtn.hidden = NO;
        detail.btnDegree.hidden = YES;
        detail.btnDisagree.hidden = YES;
        [detail updateUserStatus:msg.user];
        detail.backupLabel.text = msg.note ? [NSString stringWithFormat:@"备注：%@", msg.note] : @"备注：";
    }
}


#pragma mark - delegate

- (void) didRecieveFriendList:(FriendQueryResponseMessage*)friends
{
    if (friends && friends.resultCode == 0) {
        [self listUpdated:[GToolUtil PBArr2NSArr:friends.friendList]];
    }
    [[GAlertLoadingView sharedAlertLoadingView] hide];
}

- (void) didRecieveGroupList:(GroupQueryResponseMessage*)group
{
    if (group && group.resultCode == 0) {
        [self groupUpdated:[GToolUtil PBArr2NSArr:group.list]];
    }
    [[GAlertLoadingView sharedAlertLoadingView] hide];
}

- (void) didDeleteGroup:(GroupDeleteResponseMessage*)result
{
    if (result && result.resultCode == 0) {
        [_parser updateGroupListForUid:[GConfig getUserId]];
    } else {
        [[GAlertLoadingView sharedAlertLoadingView] hide];
        [[iToast makeText:@"删除分组失败"] show];
    }
}


#pragma mark - FriendDelDelegate

- (void)didFinishDel:(FriendDeleteResponseMessage*)result
{
    if (result && result.resultCode == 0) {
        [_parser updateFriendListForUid:[GConfig getUserId]];
    } else {
        [self failDel];
    }
}

- (void)failDel
{
    [[GAlertLoadingView sharedAlertLoadingView] show];
    [[iToast makeText:@"删除好友失败"] show];
}

@end
